package cn.lxg.service.impl;

import cn.lxg.dao.INovelDao;
import cn.lxg.dao.INovelGroupDao;
import cn.lxg.pojo.TNovel;
import cn.lxg.pojo.TNovelGroup;
import cn.lxg.service.INovelGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class NovelGroupServiceImpl implements INovelGroupService {

    @Autowired
    private final INovelGroupDao novelGroupDao = null;

    @Autowired
    private final INovelDao novelDao = null;

    @Override
    @Transactional
    public int countDataLine(TNovelGroup novelGroup) {
        return this.novelGroupDao.countDataLine(novelGroup);
    }

    @Override
    @Transactional
    public List<TNovelGroup> getList(Integer limit, Integer page, TNovelGroup novelGroup) {
        /* 计算页面 */
        Integer limitStart = null;
        Integer limitEnd = null;
        if (limit != null && page != null) {
            limitStart = (page - 1) * limit;
            limitEnd = limit;
        }
        return this.novelGroupDao.select(limitStart, limitEnd, novelGroup);
    }

    @Override
    @Transactional
    public TNovelGroup get(Integer id) {
        return this.novelGroupDao.findById(id);
    }

    @Override
    @Transactional
    public String add(TNovelGroup novelGroup) {
        novelGroup.setCreateTime(new Date());
        if (this.novelGroupDao.insert(novelGroup))
            return "创建分类成功";
        else
            return "创建分类失败";
    }

    @Override
    @Transactional
    public String delete(Integer id) {
        // 检查分类下是否存在文章
        TNovel novel = new TNovel();
        novel.setNovelGroupId(id);
        if (novelDao.countDataLine(novel) != 0) {
            return "删除分类失败，该分类下存在文章";
        }

        if (this.novelGroupDao.deleteById(id))
            return "删除分类成功";
        else
            return "删除分类失败";
    }

    @Override
    @Transactional
    public String edit(TNovelGroup novelGroup) {
        // 查旧文章
        TNovelGroup oldNovelGroup = this.novelGroupDao.findById(novelGroup.getId());

        // 更新属性
        oldNovelGroup.setName(novelGroup.getName());

        // 保存数据
        if (this.novelGroupDao.updateById(oldNovelGroup))
            return "编辑分类成功";
        else
            return "编辑分类失败";
    }
}
